﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Sykj.Infrastructure;

namespace Sykj.Services
{
    /// <summary>
    /// 广告内容
    /// </summary>
    public class Advertisement : Sykj.Repository.RepositoryBase<Sykj.Entity.Advertisement>,Sykj.IServices.IAdvertisement
    {
        ICacheService _cacheService;

        public Advertisement(Sykj.Repository.SyDbContext dbcontext, ICacheService cacheService) : base(dbcontext)
        {
            _cacheService = cacheService;
        }

        #region 根据ID获取指定条数记录
        /// <summary>
        /// 根据ID获取指定条数记录
        /// </summary>
        /// <param name="adId"></param>
        /// <param name="top"></param>
        /// <returns></returns>
        public List<Sykj.Entity.Advertisement> GetAdPostion(int adId, int top = 0)
        {
            var list = GetListByCache().AsEnumerable();
            list = list.Where(c => c.AdvPositionId == adId).OrderByDescending(c => c.AdvertisementId);
            if (top > 0)
            {
                list = list.Take(top);
            }
            return list.ToList();
        }
        #endregion

        #region 从缓存中获取数据所有集合
        /// <summary>
        /// 从缓存中获取数据所有集合
        /// </summary>
        /// <returns>返回满足查询条件的list</returns>
        public List<Sykj.Entity.Advertisement> GetListByCache()
        {
            List<Sykj.Entity.Advertisement> list = new List<Entity.Advertisement>();
            if (_cacheService.Exists(CacheKey.ADVERTISEMENTALL))
            {
                list = _cacheService.GetCache<List<Sykj.Entity.Advertisement>>(CacheKey.ADVERTISEMENTALL);
            }
            else
            {
                list = GetList().AsNoTracking().ToList();//dbcontext不进行跟踪，去缓存
                _cacheService.SetCache(CacheKey.ADVERTISEMENTALL, list);
            }
            return list;
        }
        #endregion
    }
}
